package com.azt.back.action.level;

import com.aliyun.oss.common.utils.DateUtil;
import com.azt.api.pojo.LevelRecord;
import com.azt.api.pojo.req.LevelRecordReq;
import com.azt.api.service.LevelRecordService;
import com.azt.api.service.LevelService;
import com.azt.api.service.LevelUserService;
import com.azt.back.action.BaseAction;
import com.azt.back.util.Globals;
import com.azt.model.AjaxJson;
import com.azt.model.page.Pagination;
import com.azt.utils.CommonUtil;
import com.azt.utils.RequestUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.Map;

/**
 * 等级用户
 * Created by LiQZ on 2017/4/13.
 */
@Controller
@RequestMapping("/level/user")
public class LevelUserAction extends BaseAction {

    @Autowired
    private LevelUserService levelUserService;

    @Autowired
    private LevelRecordService levelRecordService;

    @Autowired
    private LevelService levelService;

    @RequestMapping("list.do")
    public String list(Model model) {
        Map searchMap = CommonUtil.getParameterMap(request);
        int pageNo = getParaToInt("pageNo", 1);
        Pagination pagination = levelUserService.listPage(pageNo, Globals.PAGE_SIZE, searchMap);
        model.addAttribute("pagination", pagination);
        RequestUtils.MapToModelMap(searchMap, request);
        return "level/user/list";
    }

    @RequestMapping("record.do")
    public String record(LevelRecordReq recordReq, Model model) {
        int pageNo = getParaToInt("pageNo", 1);
        model.addAttribute("companyId", recordReq.getCompanyId());
        if (recordReq.getLevelType() != null) {
            model.addAttribute("levelType", recordReq.getLevelType());
        }
        if (recordReq.getBeginTime() != null) {
            model.addAttribute("beginTime", recordReq.getBeginTime());
        }
        if (recordReq.getEndTime() != null) {
            // endTime + 1 天吧
            Date endTime = DateUtils.addDays(recordReq.getEndTime(), 1);
            model.addAttribute("endTime", endTime);
        }
        Pagination pagination = levelRecordService.listPage(pageNo, Globals.PAGE_SIZE, model.asMap());
        model.addAttribute("pagination", pagination);
        return "level/user/record";
    }

    @ResponseBody
    @RequestMapping("change.do")
    public AjaxJson changeValue(LevelRecord record) {
        levelService.addAmount(null, record.getCompanyId(), record.getLevelType(), record.getType() * record.getChangeValue(), record.getChangeReason());
        return AjaxJson.success();
    }

}
